<template>
<app-layout>
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            新闻红包
            <small>活动结束后，会在5秒内，自动完成数据统计与状态关闭</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
            <li><a href="#">新闻红包</a></li>
            <li class="active">活动列表</li>
        </ol>
    </section>

    <!-- Main content -->
    <section class="content">
        <!-- Default box -->
        <div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">活动列表</h3>
            </div>
            <div class="box-body">
                <el-table
                    ref="multipleTable"
                    :data="records"
                    tooltip-effect="dark"
                    stripe
                    style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column
                    type="selection"
                    width="55">
                    </el-table-column>
                    <el-table-column
                    prop="id"
                    label="ID"
                    width="55">
                    </el-table-column>
                    <el-table-column
                    prop="name"
                    label="name"
                    show-overflow-tooltip>
                    </el-table-column>                    
                    <el-table-column
                    prop="start"
                    label="开始时间"
                    width="160">
                    </el-table-column>
                    <el-table-column
                    prop="end"
                    label="结束时间"
                    width="160">
                    </el-table-column>                     
                    <el-table-column
                    prop="credit_cost"
                    label="消耗积分"
                    width="120">
                    </el-table-column>                     
                    <el-table-column
                    prop="times_limit"
                    label="次数限制"
                    width="100">
                    </el-table-column> 
                    <el-table-column
                    prop="channels"
                    label="频道"
                    show-overflow-tooltip>
                    </el-table-column> 
                    <el-table-column
                    prop="news"
                    label="新闻"
                    show-overflow-tooltip>
                    </el-table-column>

                    <el-table-column
                    prop="status"
                    label="状态">
                    </el-table-column>                     

                    <el-table-column
                    fixed="right"
                    label="操作"
                    width="200">
                    <template slot-scope="scope">
                        <el-button @click="$router.push('/red-packet/activities/' + scope.row.id)" type="text" size="small">查看</el-button>
                        <el-button @click="editActivity(scope.row)" type="text" size="small">编辑</el-button>
                        <el-button @click="startActivity(scope.row)" type="text" size="small">开启</el-button>
                        <el-button @click="endActivity(scope.row)" type="text" size="small">关闭</el-button>
                    </template>
                    </el-table-column>    
                </el-table>
            </div>
            <!-- /.box-body -->
            <div class="box-footer">
                <!-- <el-button @click="toggleSelection()">取消选择</el-button> -->
                <el-button @click="addFormVisible=true" type="primary" size="small">添加活动</el-button>

                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total" class="pull-right">
                </el-pagination>            
            </div>
            <!-- /.box-footer-->
        </div>
        <!-- /.box -->
    </section>
    <!-- /.content -->




<el-dialog title="活动详情" :visible.sync="dialogFormVisible">
  <el-form ref="form" :model="activity" label-width="80px">
    <el-form-item label="活动名称">
      <el-input v-model="activity.name"></el-input>
    </el-form-item>

    <el-form-item label="活动时间">
      <el-date-picker
        v-model="activity.timerange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss">
      </el-date-picker>
    </el-form-item>

    <el-form-item label="消耗积分">
      <el-input v-model="activity.credit_cost"></el-input>
    </el-form-item>
    <el-form-item label="次数限制">
      <el-input v-model="activity.times_limit"></el-input>
    </el-form-item>

    <el-form-item label="频道ID">
      <el-input type="textarea" v-model="activity.channels"></el-input>
    </el-form-item>

    <el-form-item label="新闻ID">
      <el-input type="textarea" v-model="activity.news"></el-input>
    </el-form-item>    


    <el-form-item>
      <el-button type="primary" @click="submitActivity">确定</el-button>
      <el-button @click="dialogFormVisible = false">取消</el-button>
    </el-form-item>
  </el-form>
</el-dialog>



<el-dialog title="活动添加" :visible.sync="addFormVisible">
  <el-form ref="form" :model="addForm" label-width="80px">
    <el-form-item label="活动名称">
      <el-input v-model="addForm.name"></el-input>
    </el-form-item>

    <el-form-item label="活动时间">
      <el-date-picker
        v-model="addForm.timerange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss">
      </el-date-picker>
    </el-form-item>

    <el-form-item label="消耗积分">
      <el-input v-model="addForm.credit_cost"></el-input>
    </el-form-item>
    <el-form-item label="次数限制">
      <el-input v-model="addForm.times_limit"></el-input>
    </el-form-item>

    <el-form-item label="频道ID">
      <el-input type="textarea" v-model="addForm.channels" placeholder="这一版本暂不支持"></el-input>
    </el-form-item>

    <el-form-item label="新闻ID">
      <el-input type="textarea" v-model="addForm.news" placeholder="这一版本暂不支持"></el-input>
    </el-form-item>    


    <el-form-item>
      <el-button type="primary" @click="submitAddForm">确定</el-button>
      <el-button @click="addFormVisible = false">取消</el-button>
    </el-form-item>
  </el-form>
</el-dialog>

</app-layout>  
</template>

<script>
import * as API from "../../Consts/Api";
import Layout from "@/components/Layout";

export default {
  components: {
    "app-layout": Layout
  },
  data() {

    const end = new Date();
    const start = new Date();
    end.setTime(start.getTime() + 60 * 1000);

    return {    
      records: [],
      // 分页
      total: 0,
      size: 10,      
      currentPage: 1,
      // 多选
      multipleSelection: [],
      // 活动修改
      dialogFormVisible: false,
      // activity 模型
      activity: {
        id: '',
        name: '',
        credit_cost: '',
        times_limit: '',
        timerange: [start, end],
        channels: '',
        news: '',
        start: '',
        end: '',
        status: ''
      },

      // 创建活动
      addFormVisible: false,
      addForm: {
        name: '',
        credit_cost: '',
        times_limit: '',
        timerange: [],
        channels: '',
        news: '',
        start: '',
        end: '',
        status: ''
      },
    };
  },
  created: function() {
    this.loadData(this.currentPage);

    this.interval = setInterval(() => { 
        this.loadData(this.currentPage);
    }, 2000)    
  },

  beforeDestroy: function() {
    clearInterval(this.interval)
  },
    
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 分页
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    handleSizeChange(size) {
      this.size = size;
      this.loadData();
    },
    handleCurrentChange(page) {
      // console.log(`当前页: ${val}`);
      this.currentPage = page;
      this.loadData(page);
    },



    loadData(page) {
      const options = {
        params: {
          per_page: this.size,
          page: page >= 1 ? page : 1
        }
      };

      this.$http.get(API.RED_PACKET_ACTIVITIES, options).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.message,
            type: "error",
            duration: 5000
          });
        } else {
          this.records = response.data.data;
          this.total = response.data.total;
        }
      });
    },

    // 活动修改
    editActivity(row) {
      this.activity = {
        id: row.id,
        name: row.name,
        credit_cost: row.credit_cost,
        times_limit: row.times_limit,
        timerange: [row.start, row.end],
        channels: row.channels,
        news: row.news,
      }
// console.log(this.activity.timerange);
      this.dialogFormVisible = true;
    },        
    // 活动提交
    submitActivity() {
      // console.log(this.activity.timerange);
      // console.log(this.activity.timerange[0]);
      // return;
      const data = {
        id: this.activity.id,
        name: this.activity.name,
        credit_cost: this.activity.credit_cost,
        times_limit: this.activity.times_limit,
        start: this.activity.timerange[0],
        end: this.activity.timerange[1],
        channels: this.activity.channels,
        news: this.activity.news,        
      }
      this.$http.put(API.RED_PACKET_ACTIVITY.bindValue(':id', this.activity.id), data).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.message,
            type: "error",
            duration: 5000
          });
        } else {
          this.$message({
            message: response.data.message,
            type: "success",
            duration: 5000
          }); 
          
          this.dialogFormVisible = false;

          this.loadData(this.currentPage);
        }
      })
    },    

    startActivity(row) {
      this.$http.post(API.RED_PACKET_ACTIVITY_CACHES.bindValue(':id', row.id)).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.errors ? response.data.message + '<br>' + JSON.stringify(response.data.errors) : response.data.message,
            type: "error",
            duration: 5000,
            dangerouslyUseHTMLString: true
          });
        } else {
          this.$message({
            message: response.data.message,
            type: "success",
            duration: 5000
          });
          

          row.status = '开启';
        }
      })
    },
    endActivity(row) {
      this.$http.delete(API.RED_PACKET_ACTIVITY_CACHES.bindValue(':id', row.id)).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.message,
            type: "error",
            duration: 5000
          });
        } else {
          this.$message({
            message: response.data.message,
            type: "success",
            duration: 5000
          });

          row.status = '关闭';
        }
      })
    },

    // formatterStatus(row, column) {
      // if (row.status === 1) {
      //   return "进行中";
      // }

      // if (row.status === 0) {
      //   return "未知";
      // }      
    // },


    // 活动创建
    submitAddForm() {
// console.log(this.addForm.timerange);
// console.log(this.addForm.timerange[0]);
// console.log(this.addForm.timerange[1]);
// return;
      const data = {
        name: this.addForm.name,
        credit_cost: this.addForm.credit_cost,
        times_limit: this.addForm.times_limit,
        start: this.addForm.timerange[0],
        end: this.addForm.timerange[1],
        channels: this.addForm.channels,
        news: this.addForm.news,        
      }

      this.$http.post(API.RED_PACKET_ACTIVITIES, data).then(response => {
        if (response.data.status == "no") {
          this.$message({
            message: response.data.message,
            type: "error",
            duration: 5000
          });
        } else {
          this.$message({
            message: response.data.message,
            type: "success",
            duration: 5000
          }); 
          
          this.addFormVisible = false;

          this.loadData(this.currentPage);
        }
      })
    },     
  }
};
</script>